import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { LOGIN_TOKEN } from '@/globa/constants'
import router from '@/router'
import { accountLoginRequest, getUserInfoById, getUserMenusByRoleId } from '@/service/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import { firstMenu, localMenusRoutes, mapMenusToPermissions } from '@/utils/map-menus'
import userMainStore from '../main/main'

interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
  permissions: string[]
}

const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: '',
    userInfo: {},
    userMenus: [],
    permissions: []
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      try {
        // 1.登录
        const loginResult = await accountLoginRequest(account)
        const id = loginResult.data.id
        this.token = loginResult.data.token
        localCache.setCache(LOGIN_TOKEN, this.token)

        // 2.获取用户的信息
        const userInfoResult = await getUserInfoById(id)
        const userInfo = userInfoResult.data
        this.userInfo = userInfo

        // 3.根据角色请求用户的权限(菜单menus)
        const userMenuRes = await getUserMenusByRoleId(this.userInfo.role.id)
        const userMenus = userMenuRes.data
        this.userMenus = userMenus

        // 4.进行本地缓存
        localCache.setCache('userInfo', userInfo)
        localCache.setCache('userMenus', userMenus)

        //5.请求所有roles/departments数据
        const mainStore = userMainStore()
        mainStore.fetchEntireDataAction()

        // 6.获取登录用户的所有按钮的权限
        const permissions = mapMenusToPermissions(userMenus)
        this.permissions = permissions

        // 7.动态添加路由
        const routes = localMenusRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      } catch (error) {
        ElMessage.error('账号或者密码错误')
        console.log(error)
      }

      // 跳转到主页面
      router.push('/main')
    },
    loadLocalCacheAction() {
      // 1.用户刷新默认进行加载数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 1..请求所有roles/departments数据
        const mainStore = userMainStore()
        mainStore.fetchEntireDataAction()

        // // 2.获取按钮的权限
        const permissions = mapMenusToPermissions(userMenus)
        this.permissions = permissions

        // 动态添加路由
        const routes = localMenusRoutes(userMenus)

        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})

export default useLoginStore
